package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

//工具类
public final class JDBCUtil {// DBTool
	
	private JDBCUtil() {
		
	}
	
	private static ResourceBundle rb = ResourceBundle.getBundle("dao.jdbc");	//读取配置文件
	
	private static String driver = rb.getString("driver");						//读取文件中的每一个属性
	private static String url = rb.getString("url");
	private static String user = rb.getString("user");
	private static String pass = rb.getString("pass");
	
	static {//此处使用静态代码块加载驱动，因为此条语句必须在程序一开始就执行并且只需执行一次
		try {
			Class.forName(driver);					
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static Connection getConnection() throws SQLException {	//throws抛异常的，连接数据库
		return DriverManager.getConnection(url,user,pass);			//捕获范围是在方法
	}		
	
	public static Connection getConnection1()  {					//try catch的抛异常的连接数据库稳定版
		try {														//捕获方法在try中
			return DriverManager.getConnection(url,user,pass);		//更推荐使用此种，减小了异常的范围
		} catch (SQLException e) {
			e.printStackTrace();
		//throw new MyException();	//抛出自己定义的异常
		}
		return null;
	}
	
	
	
	public static void close(Connection conn,Statement st) {		//普通的断开链接
		close(conn,null);
	}
	
	public static void close(Connection conn,Statement st,ResultSet rs) {//稳定的抛异常断连
		try {
			if(rs != null) {
				rs.close();
				rs = null;
			}
			if(st != null) {
				st.close();
				st = null;
			}
			if(conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws SQLException {
		Connection conn = JDBCUtil.getConnection();
		System.out.println(conn);
		
		conn.createStatement();
		conn.prepareStatement("");
		
		JDBCUtil.close(conn, null); 
	}

}
